/**
 * React JSX TASK
 * @Author: jiangcheng198745@hotmail.com
 * @Date: 2016/08/08
 */

import gulp from 'gulp';
import {log, colors}  from 'gulp-util';
import browserify from 'browserify';
import babelify from 'babelify';
import {reload} from 'browser-sync';
import source from 'vinyl-source-stream';

import config from '../gulp.config';
import messageLogger from '../utils/message.gulp';
import logWatch from '../utils/logWatch.gulp'

gulp.task('browserify', () => {

    messageLogger('Browserify JSX files');
    return browserify({
        entries: config.entries,
        extensions: config.extensions,
        debug: true,
        basedir: config.app
    })
    .transform(babelify, {
        presets: [
            'es2015',
            'react',
            'stage-0'
        ],
        plugins: [
            "transform-decorators-legacy"
        ]
    })
    .bundle()
    .on('error', (error) => {
        log(colors.red(error.toString()));
        this.emit('end');
    })
    .pipe(source(config.distEntry))
    .pipe(gulp.dest(config.build))
    .pipe(reload({
        stream: true
    }));
});

gulp.task('watch:jsx', () => {
    gulp.watch([
        config.appFiles.jsx
    ], [
        'browserify'
    ])
    .on('change', logWatch);
});